package com.dyzx.hbb.modules.wms.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dyzx.hbb.aliyun.product.ProductClient;
import com.dyzx.hbb.common.base.PageQuery;
import com.dyzx.hbb.common.base.PageResult;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseValidController;
import com.dyzx.hbb.modules.wms.entity.WmsHouse;
import com.dyzx.hbb.modules.wms.entity.WmsProduct;
import com.dyzx.hbb.modules.wms.entity.WmsProductTask;
import com.dyzx.hbb.modules.wms.query.WmsProductQuery;
import com.dyzx.hbb.modules.wms.service.WmsProductService;
import com.dyzx.hbb.modules.wms.service.WmsProductTaskService;
import com.dyzx.hbb.modules.wms.vo.WmsProductTaskVO;
import com.dyzx.hbb.modules.wms.vo.WmsProductUVO;
import com.dyzx.hbb.modules.wms.vo.WmsProductVO;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 产品管理控制器
 * <p>处理仓库管理系统中产品的CRUD操作和相关业务逻辑
 * <p>主要职责：
 * <ul>
 * <li>提供产品的增删改查接口</li>
 * <li>支持按条件查询产品列表</li>
 * <li>提供产品详情查询功能</li>
 * <li>实现库存相关的产品查询</li>
 * <li>支持按编号查询产品信息</li>
 * </ul>
 *
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
@Tag(name = "产品管理", description = "产品相关接口")
@RestController
@RequestMapping("/wms/product")
public class WmsProductController extends BaseValidController<
        WmsProductService,       // 服务接口类型
        WmsProduct,              // 实体类类型
        WmsProductQuery,         // 查询参数类型
        WmsProductVO,            // 添加参数类型
        WmsProductUVO            // 更新参数类型
        > {

    @Autowired
    private WmsProductService service;
    @Autowired
    private ProductClient productClient;


    @Autowired
    private WmsProductTaskService taskService;

    @Override
    protected WmsProductService getBaseService() {
        return service;
    }

    @Override
    protected MyLambdaQueryWrapper<WmsProduct> queryWrapper(WmsProductQuery query) {
        MyLambdaQueryWrapper<WmsProduct> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(WmsProduct::getId)
                .select(WmsProduct::getName)
                .select(WmsProduct::getInternalCode)
                .select(WmsProduct::getStatus)
                .select(WmsProduct::getCreateDate)
                .select(WmsProduct::getUpdateDate)
                .select(WmsProduct::getCategoryId)
                .select(WmsProduct::getSupplierId)
                .select(WmsProduct::getUnitOfMeasure)
                .select(WmsProduct::getWeight)
                .select(WmsProduct::getDimensions)
                .select(WmsProduct::getImageUrl)
                .select(WmsProduct::getIsActive)
                .select(WmsProduct::getQualityTraceFlag)
                .select(WmsProduct::getAmt)
                .select("0").as("quantity")
                .select(WmsProduct::getStandardCompliance);
        queryWrapper.orderByDesc(WmsProduct::getCreateDate);
        queryWrapper.select("(SELECT name FROM wms_product_category where id = wms_product.category_id LIMIT 1)").as("category_name");

        if (query != null) {
            queryWrapper.likeRight(query.getName() != null, WmsProduct::getName, query.getName())
                    .likeRight(query.getInternal_code() != null, WmsProduct::getInternalCode, query.getInternal_code())
                    .eq(query.getCategory_id() != null, WmsProduct::getCategoryId, query.getCategory_id())
                    .eq(query.getStatus() != null, WmsProduct::getStatus, query.getStatus());
        }
        return queryWrapper;
    }

    @Operation(summary = "获取产品详情", description = "根据查询条件获取产品详情信息")
    @Override
    protected MyLambdaQueryWrapper<WmsProduct> queryInfoWrapper() {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<WmsProduct> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(WmsProduct::getId)
                .select(WmsProduct::getName)
                .select(WmsProduct::getInternalCode)
                .select(WmsProduct::getStatus)
                .select(WmsProduct::getCreateDate)
                .select(WmsProduct::getUpdateDate)
                .select(WmsProduct::getCategoryId)
                .select(WmsProduct::getSupplierId)
                .select(WmsProduct::getUnitOfMeasure)
                .select(WmsProduct::getWeight)
                .select(WmsProduct::getDimensions)
                .select(WmsProduct::getImageUrl)
                .select(WmsProduct::getIsActive)
                .select(WmsProduct::getDescription)
                .select(WmsProduct::getOrganId)
                .select(WmsProduct::getStandardCompliance)
                .select(WmsProduct::getGrossweight)
                .select(WmsProduct::getNetweight)
                .select(WmsProduct::getWidth)
                .select(WmsProduct::getHeight)
                .select(WmsProduct::getDepth)
                .select(WmsProduct::getOrigincountry)
                .select(WmsProduct::getOriginplace)
                .select(WmsProduct::getAssemblycountry)
                .select(WmsProduct::getCompany)

                .select(WmsProduct::getEname)
                .select(WmsProduct::getUnspsc)
                .select(WmsProduct::getBrand)
                .select(WmsProduct::getNetcontent)
                .select(WmsProduct::getImageId)
                .select(WmsProduct::getDeleted)
                .select(WmsProduct::getOperatorId)
                .select(WmsProduct::getQualityTraceFlag)
                .select(WmsProduct::getQualityTraceFlag)
                .select(WmsProduct::getAmt).as("amt_old")
                //wms_product_task return:amt  organ_id=organId and product_id=wms_product.id
                .select("IFNULL((SELECT  SUM(amt) FROM `wms_product_task` where product_id=wms_product.id and  `organ_id` = " + organId + "),0)").as("amt")
                .select("IFNULL((SELECT  SUM(quantity) FROM `wms_inventory` where product_id=wms_product.id and  `organ_id` = " + organId + "),0)").as("quantity")
                .select(WmsProduct::getStandardCompliance);
        queryWrapper.select("(SELECT name FROM wms_product_category where id = wms_product.category_id LIMIT 1)").as("category_name");
        queryWrapper.orderByDesc(WmsProduct::getCreateDate);
        return queryWrapper;
    }

    @Override
    protected WmsProduct addValid(WmsProductVO entity) {
        return null;
    }

    @Override
    protected WmsProduct editValid(WmsProductUVO entity) {
        return null;
    }

    //GET: getNo
    @Operation(summary = "根据编号查询")
    @GetMapping("no/{no}")
    public Result<Map<String, Object>> getNo(@PathVariable String no) {
        if (no == null) {
            return Result.error(400, "参数错误");
        }
        MyLambdaQueryWrapper<WmsProduct> queryWrapper = queryInfoWrapper();

        queryWrapper.eq(WmsProduct::getInternalCode, no);
        //wms_inventory  product_id=wms_product.id and house_id=house_id
        queryWrapper.last("limit 1");
        Map<String, Object> map = service.getMap(queryWrapper);
        if (map == null) {
            WmsProduct p = productClient.send(no);
            if (p != null) {
                boolean save = service.save(p);
                if (save) {
                    MyLambdaQueryWrapper<WmsProduct> queryWrapper1 = queryInfoWrapper();
                    queryWrapper1.eq(WmsProduct::getInternalCode, no);
                    queryWrapper1.last("limit 1");
                    Map<String, Object> map1 = service.getMap(queryWrapper1);
                    return Result.ok(map1);
                } else {
                    return Result.error(500, "保存数据失败");
                }

            } else {
                return Result.error(404, "暂无数据");
            }
        } else {
            return Result.ok(map);
        }


    }

    @Operation(summary = "根据编号查询")
    @GetMapping("out/no/{no}")
    public Result<Map<String, Object>> getOutNo(@PathVariable String no, @RequestParam(required = false, defaultValue = "0", name = "house_id") Long house_id) {
        if (no == null || house_id == null || house_id == 0) {
            return Result.error(400, "参数错误");
        }
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<WmsProduct> queryWrapper = queryInfoWrapper();
        queryWrapper.eq(WmsProduct::getInternalCode, no);
        queryWrapper.last("limit 1");
        queryWrapper.inSql(WmsProduct::getId, "(SELECT  product_id FROM `wms_inventory` where  `house_id` = " + house_id + " and `organ_id` = " + organId + "  and  quantity > 0)");
        Map<String, Object> map = service.getMap(queryWrapper);
        return map == null ? Result.error(404, "暂无数据") : Result.ok(map);

    }

    /*
     * 仓库商品
     * 接口：inventory
     * 参数：PageQuery pageQuery
     *
     * */
    @GetMapping("/inventory")
    public Result<Map<String, Object>> inventory(PageQuery pageQuery) {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<WmsProduct> queryWrapper = queryInfoWrapper();
        queryWrapper.inSql(WmsProduct::getId, "(SELECT  product_id FROM `wms_inventory` where  `organ_id` = " + organId + "  and  quantity > 0)");
        Page<Map<String, Object>> mapPage = this.service.pageMaps(createPage(pageQuery), queryWrapper);
        return PageResult.parsePage(mapPage);
    }

    @GetMapping("/mini_list")
    public Result<List<Map<String, Object>>> miniList(@RequestParam(required = false, defaultValue = "0", name = "house_id") Long house_id) {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<WmsProduct> queryWrapper = queryInfoWrapper();
        queryWrapper.select(WmsProduct::getId)
                .select(WmsProduct::getName)
                .select(WmsProduct::getImageUrl)
                .select(WmsProduct::getInternalCode);

        if (house_id > 0) {
            queryWrapper.inSql(WmsProduct::getId, "(SELECT  product_id FROM `wms_inventory` where  `house_id` = " + house_id + " and `organ_id` = " + organId + "  and  quantity > 0)");
            queryWrapper.select("IFNULL((SELECT  SUM(quantity) FROM `wms_inventory` where product_id=wms_product.id and  `house_id` = " + house_id + " and `organ_id` = " + organId + "),0)").as("quantity");

        } else {
            queryWrapper.inSql(WmsProduct::getId, "(SELECT  product_id FROM `wms_inventory` where  `organ_id` = " + organId + "  and  quantity > 0)");
            queryWrapper.select("IFNULL((SELECT  SUM(quantity) FROM `wms_inventory` where product_id=wms_product.id and  `organ_id` = " + organId + "),0)").as("quantity");
        }
        //wms_product_task  organ_id=organId and product_id=wms_product.id and status=1
        queryWrapper.inSql(WmsProduct::getId, "(SELECT  product_id FROM `wms_product_task` where  `organ_id` = " + organId + " and `status` = 1)");
        List<Map<String, Object>> maps = this.service.listMaps(queryWrapper);
        if (maps.isEmpty()) {
            return Result.error(404, "暂无数据");
        }
        return Result.ok(maps);
    }

    // PUT taskUpdate
    @Operation(summary = "更新任务")
    @PutMapping("/update_task")
    public Result<Boolean> taskUpdate(@RequestBody WmsProductTaskVO entity) {
        if (entity == null) {
            return Result.error(400, "参数错误");
        }
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<WmsProductTask> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(WmsProductTask::getProductId, entity.getProductId());
        queryWrapper.eq(WmsProductTask::getOrganId, organId);
        queryWrapper.last("limit 1");
        WmsProductTask task = taskService.getOne(queryWrapper);
        if (task == null) {
            task = new WmsProductTask();
            task.setProductId(entity.getProductId());
            task.setOrganId(organId);
          //  task.setStatus(1);
            task.setCreateDate(System.currentTimeMillis());
            task.setUpdateDate(System.currentTimeMillis());
            task.setOperatorId(SecurityContextHolder.getUserId());
            task.setAmt(entity.getAmt());
            task.setAmtOld(entity.getAmtOld());
        } else {
            task.setUpdateDate(System.currentTimeMillis());
            task.setOperatorId(SecurityContextHolder.getUserId());
            task.setAmt(entity.getAmt());
            task.setAmtOld(entity.getAmtOld());
        }
        boolean update = taskService.saveOrUpdate(task);
        return update ? Result.ok(update) : Result.error(500, "更新数据失败");
    }


    @Operation(summary = "简易列表")
    @GetMapping("/mini_brand_list")
    public Result<List<Map<String, Object>>> miniList(
            @RequestParam(required = false, defaultValue = "0", name = "type") Integer type
    ) {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<WmsProduct> wrapper = new MyLambdaQueryWrapper<>();
        if(type==1){
            wrapper.select(WmsProduct::getId);
            wrapper.select(WmsProduct::getCompany).as("name");
            wrapper.select(WmsProduct::getCompany).as("label");
            wrapper.select(WmsProduct::getCompany).as("value");
            wrapper.groupBy(WmsProduct::getCompany);
            wrapper.isNotNull(WmsProduct::getCompany);
        }else {
            wrapper.select(WmsProduct::getId);
            wrapper.select(WmsProduct::getBrand).as("label");
            wrapper.select(WmsProduct::getBrand).as("name");
            wrapper.select(WmsProduct::getBrand).as("value");
            wrapper.groupBy(WmsProduct::getBrand);
            wrapper.isNotNull(WmsProduct::getBrand);

        }

        wrapper.orderByDesc(WmsProduct::getId);

        List<Map<String, Object>> list = getBaseService().listMaps(wrapper);
        return list.isEmpty() ? Result.error(404, "暂无数据") : Result.ok(list);
    }
}